// pages/register/register.js
const app = getApp();
const $api = require('../../request/api.js').API;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    registerForm: {
      // 用户名
      username: "",
      // 密码
      userpassword: "",
      // 二次密码
      secondpwd: "",
      // 验证码
      verifyCode: ""
    },
    errorMessage: {
      username: "",
      userpassword: "",
      secondpwd: "",
      verifyCode: ""
    }
  },

  // 切换验证码图片
  changeVerifyCode () {
    this.setData({
      verifyCode_prc: this.timestamp("http://localhost:9000/user/verifyCode")
    })
  },

  onLoad () {
    // 页面加载时顺便加载验证码图片
    this.setData({
      verifyCode_prc: this.timestamp("http://localhost:9000/user/verifyCode")
    })
  },

 //为url添加时间戳
 timestamp (url) {
    var getTimestamp = new Date().getTime();
    if (url.indexOf("?") > -1) {
        url = url + "&timestamp=" + getTimestamp
    } else {
        url = url + "?timestamp=" + getTimestamp
    }
    return url;
  },

  // 注册
  toRegister () {
    if (this.data.errorMessage.username === "" && this.data.errorMessage.userpassword === "" && this.data.errorMessage.secondpwd === "" && this.data.errorMessage.verifyCode === "") {
      let data = {
        username: this.data.registerForm.username,
        userpassward: this.data.registerForm.userpassword,
        verifyCode: this.data.registerForm.verifyCode
      }

      // 这里发起注册请求
      $api.register(data).then(res => {
        
      });
    }
    
  },

  // 检查用户名
  usernameCheck (event) {
    const username = event.detail.value;
    let result = "";
    if (username === "") result = '用户名不能为空';
    this.setData({
      'errorMessage.username': result,
      'registerForm.username': username
    });
  },
  // 检查密码
  userpasswordCheck (event) {
    const userpassword = event.detail.value;
    let result = "";
    if (userpassword === "") result = '密码不能为空';
    if (userpassword.length < 8 || userpassword.length > 12) result = '密码为8-12位英文和数字';
    this.setData({
      'errorMessage.userpassword': result,
      'registerForm.userpassword': userpassword
    });
  },
  secondpwdCheck (event) {
    const secondpwd = event.detail.value;
    let result = "";
    console.log(this.data.registerForm.userpassword);
    console.log(secondpwd);
    if (this.data.registerForm.userpassword !=="" && secondpwd !== this.data.registerForm.userpassword)  result = '两次密码输入不一样';
    if (secondpwd.length < 8 || secondpwd.length > 12) result = '密码为8-12位英文和数字';
    this.setData({
      'errorMessage.secondpwd': result,
      'registerForm.secondpwd': secondpwd
    });
  },
  verifyCodeCheck (event) {
    const verifyCode = event.detail.value;
    let result = "";
    if (verifyCode === "") result="验证码不能为空";

    this.setData({
      'errorMessage.verifyCode': result,
      'registerForm.verifyCode': verifyCode
    });
  }
})